import { APP_CONFIG } from '../config/index';
console.log('config', APP_CONFIG)
export const fetchService = async (url, options = {}) => {
  // 基础URL
  // const baseUrl = process.env.VUE_APP_BASE_API;
  
  const baseUrl = APP_CONFIG.BASE_URL;
  const fullUrl = url.startsWith('http') ? url : `${baseUrl}${url}`;

  // 请求拦截器
  const onRequest = (config) => {
    const authToken = window.localStorage.getItem('Authorization');
    // 如果请求体是 FormData，则不设置 'Content-Type'
    const isFormData = config.body instanceof FormData;
    return {
      ...config,
      headers: {
        ...(authToken ? { 'Authorization-Token': authToken } : {}),
        ...config.headers,
        ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
      },
    };
  };

  // 响应拦截器
  const onResponse = async (response) => {
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || `Request failed with status ${response.status}`);
    }
    return response;
  };

  // 处理请求
  const config = onRequest(options);

  const executeFetch = async () => {
    try {
      // 发起请求
      const response = await fetch(fullUrl, config);

      // 处理响应
      const processedResponse = await onResponse(response);

      // 解析响应数据
      const res = await processedResponse.json();

      if(res.success){
        return res
      }
      switch (res.code) {
        case 501:
          console.log('请登录');
          setTimeout(() => {
            window.location = '#/login/';
          }, 1500);
          break;
        case 502:
          console.log('网站内部错误，请联系网站维护人员');
          break;
        case 401:
          console.log('参数不对');
          break;
        case 402:
          console.log('参数值不对');
          break;
        case 0:
          return res;
        default:
          // 非5xx的错误属于业务错误，留给具体页面处理
          throw response;
      }
      throw new Error('error');
    } catch (error) {
      console.log('连接超时', error); // for debug
      throw error;
    }
  };
  return executeFetch();
};